package cn.leven.web.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/cookie-demo2")
public class CookieDemo2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie[] cookie = request.getCookies() ;
        String lastTime="";
        if(cookie!=null){
            for (Cookie c : cookie){
                String name = c.getName();
                String value = c.getValue();
                System.out.println(name+':'+value);
                if(name.equals("lastTime")){
                    lastTime = value;
                }
            }
        }
        response.setContentType("text/html;charset=utf-8");
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        String str_date = simpleDateFormat.format(date);
        Cookie cookie1 = new Cookie("lastTime",URLEncoder.encode(str_date, "utf-8"));
        cookie1.setMaxAge(86000*30);
        response.addCookie(cookie1);
        if(lastTime.equals("") ){
            response.getWriter().write("欢迎您，访问本网站");
        }else{
            response.getWriter().write("欢迎回来，您上次访问时间为"+ URLDecoder.decode(lastTime,"utf-8"));
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
